package com.example.security.validate;

import com.example.security.exception.ValidateCodeException;
import com.example.security.validate.image.ImageCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("validateCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter{

	/*
	 * 验证码失败处理器
	 */
	@Autowired
	private AuthenticationFailureHandler loginAuthenticationFailureHandler;

	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		if(StringUtils.endsWithIgnoreCase("/login",request.getRequestURI())
				&& StringUtils.endsWithIgnoreCase(request.getMethod(),"post")){
			try {
				validate(new ServletWebRequest(request));
			} catch(ValidateCodeException e) {
				loginAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
				return;
			}
		}
      
		filterChain.doFilter(request, response);
	}

	private void validate(ServletWebRequest request) throws ServletRequestBindingException {
		ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request,"SESSION_KEY_IMAGE_CODE");
		String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),"imageCode");

		if (StringUtils.isBlank(codeInRequest)) {
			throw new ValidateCodeException("验证码的值不能为空");
		}

		if (codeInSession == null) {
			throw new ValidateCodeException("验证码不存在");
		}

		if (codeInSession.isExpried()) {
			sessionStrategy.removeAttribute(request, "SESSION_KEY_IMAGE_CODE");
			throw new ValidateCodeException("验证码已过期");
		}

		if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
			throw new ValidateCodeException("验证码不匹配");
		}

		sessionStrategy.removeAttribute(request, "SESSION_KEY_IMAGE_CODE");
	}

}

